const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('path');
const { exec } = require('child_process');

function createWindow() {
  const win = new BrowserWindow({
    width: 900,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      nodeIntegration: false,
      contextIsolation: true
    }
  });
  win.loadFile('index.html');
}

app.whenReady().then(() => {
  createWindow();
  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
  });
});

app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit();
});

// 获取所有磁盘信息（结合类型和盘符信息）
ipcMain.handle('get-disks', async () => {
  return new Promise((resolve) => {
    // 先获取物理磁盘信息（包含类型）
    exec('powershell -Command "Get-PhysicalDisk | Select-Object FriendlyName,DeviceId,MediaType,OperationalStatus,Size | ConvertTo-Json"', (err, stdout) => {
      if (err) {
        console.error('获取物理磁盘信息失败:', err);
        return resolve([]);
      }
      
      try {
        // 解析物理磁盘信息
        let physicalDisks = [];
        try {
          const parsedDisks = JSON.parse(stdout.trim());
          physicalDisks = Array.isArray(parsedDisks) ? parsedDisks : [parsedDisks];
        } catch (e) {
          console.error('解析物理磁盘信息失败:', e, stdout);
          return resolve([]);
        }
        
        // 将物理磁盘信息转换为磁盘编号映射
        const diskMap = {};
        physicalDisks.forEach(disk => {
          diskMap[disk.DeviceId] = {
            FriendlyName: disk.FriendlyName,
            DeviceId: disk.DeviceId,
            MediaType: disk.MediaType || '',
            OperationalStatus: disk.OperationalStatus,
            Size: disk.Size,
            DriveLetters: ''
          };
        });
        
        // 获取所有磁盘信息（编号）
        exec('powershell -Command "Get-Disk | Select-Object Number,UniqueId | ConvertTo-Json"', (err2, stdout2) => {
          if (err2) {
            console.error('获取磁盘编号失败:', err2);
            return resolve(Object.values(diskMap));
          }
          
          try {
            // 解析磁盘编号
            let disks = [];
            try {
              const parsedDisks = JSON.parse(stdout2.trim());
              disks = Array.isArray(parsedDisks) ? parsedDisks : [parsedDisks];
            } catch (e) {
              console.error('解析磁盘编号失败:', e);
              return resolve(Object.values(diskMap));
            }
            
            // 创建DeviceId到Number的映射
            const diskNumberMap = {};
            disks.forEach(disk => {
              // 尝试找到对应的物理磁盘
              for (const deviceId in diskMap) {
                if (deviceId == disk.Number) { // 故意使用非严格相等
                  diskNumberMap[deviceId] = disk.Number;
                  break;
                }
              }
            });
            
            // 获取分区和盘符
            exec('powershell -Command "Get-Partition | Select-Object DiskNumber,DriveLetter | ConvertTo-Json"', (err3, stdout3) => {
              if (err3) {
                console.error('获取分区信息失败:', err3);
                return resolve(Object.values(diskMap));
              }
              
              try {
                // 解析分区信息
                let partitions = [];
                try {
                  const parsedPartitions = JSON.parse(stdout3.trim());
                  partitions = Array.isArray(parsedPartitions) ? parsedPartitions : [parsedPartitions];
                } catch (e) {
                  console.error('解析分区信息失败:', e);
                  return resolve(Object.values(diskMap));
                }
                
                // 添加盘符信息到磁盘
                partitions.forEach(partition => {
                  if (partition.DriveLetter && partition.DiskNumber !== null) {
                    const deviceId = String(partition.DiskNumber);
                    if (diskMap[deviceId]) {
                      if (diskMap[deviceId].DriveLetters) {
                        diskMap[deviceId].DriveLetters += ', ' + partition.DriveLetter;
                      } else {
                        diskMap[deviceId].DriveLetters = partition.DriveLetter;
                      }
                    }
                  }
                });
                
                // 返回所有磁盘信息，按盘符排序
                const result = Object.values(diskMap);
                result.sort((a, b) => {
                  if (!a.DriveLetters && !b.DriveLetters) return 0;
                  if (!a.DriveLetters) return 1;
                  if (!b.DriveLetters) return -1;
                  return a.DriveLetters.localeCompare(b.DriveLetters);
                });
                
                resolve(result);
              } catch (e) {
                console.error('处理分区信息时出错:', e);
                resolve(Object.values(diskMap));
              }
            });
          } catch (e) {
            console.error('处理磁盘编号时出错:', e);
            resolve(Object.values(diskMap));
          }
        });
      } catch (e) {
        console.error('处理物理磁盘信息时出错:', e);
        resolve([]);
      }
    });
  });
});

// 批量脱机操作
ipcMain.handle('offline-disks', async (event, deviceIds) => {
  return new Promise((resolve) => {
    const script = deviceIds.map(id => `Set-Disk -Number ${id} -IsOffline $true`).join('; ');
    exec(`powershell -Command "${script}"`, (err) => {
      resolve(!err);
    });
  });
});

// 批量联机操作
ipcMain.handle('online-disks', async (event, deviceIds) => {
  return new Promise((resolve) => {
    const script = deviceIds.map(id => `Set-Disk -Number ${id} -IsOffline $false`).join('; ');
    exec(`powershell -Command "${script}"`, (err) => {
      resolve(!err);
    });
  });
});
